package com.partners.component.aop;

import com.partners.annotation.Token;
import com.partners.configure.TokenConfig;
import com.partners.constant.ErrorMessageEnum;
import com.partners.model.BusinessException;
import com.partners.model.Member;
import com.partners.model.TokenCodeModel;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author liangyongle
 * @date 2019-01-14
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class TokenAop {

    @Resource
    private TokenConfig tokenConfig;

    @Pointcut("@annotation(com.partners.annotation.Token)")
    public void tokenVaildService(){}

    @Around("tokenVaildService()")
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method currentMethod = methodSignature.getMethod();
        if (currentMethod.getDeclaredAnnotation(Token.class) == null) {
            return proceedingJoinPoint.proceed();
        }

        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String token = request.getHeader("token");
        if(token != null){
            Member member = new Member();
            member.setToken(token);
            TokenCodeModel andSaveToken = tokenConfig.createAndSaveToken(member);
            Integer nowTime = TimestampUtils.timestamp();
            Integer overTime = andSaveToken.getOverTime();
            if(nowTime < overTime){
                //延长过期时间  todo
                return proceedingJoinPoint.proceed();

            }else{
                throw BusinessException.of(ErrorMessageEnum.TOKEN_IS_OVERTIME);
            }
        }else{
            throw BusinessException.of(ErrorMessageEnum.TOKEN_NOT_FOUND);
        }
    }

}
